# -*- encoding: utf-8 -*-
import time
import wizard
import netsvc
import pooler
from osv import fields, osv
from tools.translate import _
from osv.orm import browse_record, browse_null
import datetime

class aas_study_result_report_wizard(wizard.interface):
	_form_template = '''
		<form string="%s">
			<field name="readonly" invisible="1"/>
			<field name="student_id" attrs="{'readonly':[('readonly', '=', True)]}"/>
			<field name="type"/>
			<newline/>
			<field name="year" context="{'filter_on_year':year}"/>
			<field name="semester" context="{'filter_on_year':year}"/>
			<newline/>
			<label string="%s" colspan="4"/>
			<newline/>
			<field name="results" colspan="4" nolabel="1"/>
			<newline/>
			<group colspan="4" col="10">
				<label string="" colspan="8"/>
				<field name="gpa" colspan="2"/>
			</group>
    	</form>
	'''
	_form = _form_template % (_('Study Result'), _('Please remember to click on button Update after changing above information to see the correct result.'))
	
	_fields = {
		'student_id': {'type': 'many2one', 'string': _('Student'), 'relation': 'res.users', 'domain': "[('type', '=', 'student')]"},
		'type': {'type': 'selection', 'string': _('Result Format'), 'required': True, 'selection': [('full', _('Full')), ('compact', _('Compact'))], 'default': 'full'},
		'year': {'type': 'many2one', 'string': _('Year'), 'relation': 'aas.academic.year'},
		'semester': {'type': 'many2one', 'string': _('Semester'), 'relation': 'aas.academic.semester'},
		'readonly': {'type': 'boolean', 'string': ''},
		'year': {'type': 'many2one', 'string': _('Year'), 'relation': 'aas.academic.year'},
		'results': {'type': 'many2many', 'string': _('Details'), 'relation': 'study.result', 'readonly': True},
		'gpa': {'type': 'float', 'string': _('Average Point'), 'digits': (16, 2), 'readonly': True},
	}
	
	def _init(self, cr, uid, data, context):
		res = {'readonly': False}
		if not context:
			context = {}
		pool = pooler.get_pool(cr.dbname)
		user_obj = pool.get('res.users')
		result_obj = pool.get('study.result')
		
		all_current_results = result_obj.search(cr, uid, [])
		result_obj.unlink(cr, uid, all_current_results)
		
		user = user_obj.browse(cr, uid, uid, context=context)
		
		year_id = False
		semester_id = False
		student_id = uid
		type = 'full'
		form = data.get('form', False)
		if form:
			year_id = form.get('year', False)
			student_id = form.get('student_id', False)
			semester_id = form.get('semester', False)
			type = form.get('type', 'full')
		
		study_results = user_obj.get_study_result(cr, uid, student_id, year_id, semester_id, type, context=context)
		results_ids = []
		for year_name in study_results['details'].keys():
			for semester_name in study_results['details'][year_name].keys():
				for line in study_results['details'][year_name][semester_name]:
					result_data = {
						'year': line[0],
						'semester': line[1],
						'subject_code': line[2],
						'subject_name': line[3],
						'th_credit': line[4],
						'pr_credit': line[5],
						'total_credit': line[6],
						'mark': line[7],
						'note': line[8],
						'does_pass': line[9],
					}
					id = result_obj.create(cr, uid, result_data, context=context)
					results_ids.append(id)
		gpa = study_results.get('gpa', 0.00)
		res.update({'results': results_ids, 'student_id': student_id, 'year': year_id, 'semester': semester_id, 'gpa': str(gpa)})
		return res
	
	def print_report(self, cr, uid, data, context):
		datas = {}
		datas['model'] = 'res.users'
		student_id = data['form']['student_id']
		year_id = data['form']['year']
		semester_id = data['form']['semester']
		type = data['form']['type']
		
		pool = pooler.get_pool(cr.dbname)
		user_obj = pool.get('res.users')
		
		study_results = user_obj.get_study_result(cr, uid, student_id, year_id, semester_id, type, context=context)
		
		datas['id'] = student_id
		datas['ids'] = [student_id]
		datas['form'] = {'ids': [student_id]}
		datas['context'] = {'study_results': study_results, 'student_id': student_id}
		return {'type': 'ir.actions.report.xml', 'report_name': 'aas_study_result_report', 'datas': datas}
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('update', _('Update'), 'gtk-ok', True),																				
																				('print', _('Print'), 'gtk-print', True),]},
		},
		'update': {
			'actions': [],
			'result': {'type': 'state', 'state': 'init'},
		},
		'print': {
			'actions': [],
			'result': {'type': 'action', 'action': print_report, 'get_id_from_action': True, 'state': 'end'},
		},
	}	
aas_study_result_report_wizard("aas_study_result_report_wizard")


class study_result(osv.osv_memory):
	
	def function_computed(self, cr, uid, ids, field_name, args, context=None):
		res = {}
		for result in self.browse(cr, uid, ids, context=context):
			res.update({result.id: result.total_credit * result.mark})
		return res
	
	_name = 'study.result'
	_columns = {
		'name': fields.char('/', size=8),
		'year': fields.char('Year', size=64),
		'semester': fields.char('Semester', size=64),
		'subject_code': fields.char('Subject Code', size=64),
		'subject_name': fields.char('Subject Name', size=64),
		'th_credit': fields.integer('Theoretical Credit'),
		'pr_credit': fields.integer('Practical Credit'),
		'total_credit': fields.integer('Total Credit'),
		'mark': fields.float('Mark', digits=(16,2)),
		'computed': fields.function(function_computed, method=True, type='float', string='Computed'),
		'note': fields.char('Note', size=64),
		'does_pass': fields.boolean('Does Pass'),
	}
	_defaults = {
		'name': lambda *a: '/',
	}
study_result()